const DB_NAME = 'reservoir'
const DB_VERSION = 1
const DB_STORE_NAME = 'model_glb'

export class DBUtil {
	// 获取模型数据
	async get(url) {
		this.db = await this.initDataBase()
		const request = this.db.transaction([DB_STORE_NAME], 'readwrite').objectStore(DB_STORE_NAME).get(url),
			that = this

		return new Promise((resolve, reject) => {
			request.onsuccess = function (event) {
				let modelFile = event.target.result
				// 假如已经有缓存了 直接用缓存
				if (modelFile) {
					resolve(modelFile.blob)
				} else {
					// 假如没有缓存 请求新的模型存入
					that
						.put(url)
						.then((blob) => {
							resolve(blob)
						})
						.catch(() => {
							reject()
						})
				}
			}
			request.onerror = function (event) {
				console.log('error', event)
				reject()
			}
		})
	}
	// 存储模型数据
	async put(url) {
		let rs = await fetch(url, { method: 'get' })
		if (rs.status == 200) {
			let blob = null
			try {
				blob = await rs.arrayBuffer()
			} catch (e) {
				console.log('请求arrayBuffer失败,用blob方式')
				rs = await fetch(url, { method: 'get' })
				blob = await rs.blob()
			}
			let obj = {
				model: url
			}
			obj.blob = new Blob([blob])
			let inputRequest = this.db.transaction([DB_STORE_NAME], 'readwrite').objectStore(DB_STORE_NAME).add(obj)
			return new Promise((resolve, reject) => {
				inputRequest.onsuccess = function () {
					resolve(obj.blob)
				}
				inputRequest.onerror = function (evt) {
					reject()
				}
			})
		}
	}
	// 删除模型
	async delete(url) {
		this.db = await this.initDataBase()
		let request = this.db.transaction([DB_STORE_NAME], 'readwrite').objectStore(DB_STORE_NAME).delete(url)
		return new Promise((resolve, reject) => {
			request.onsuccess = function (event) {
				resolve()
			}
			request.onerror = function (event) {
				reject()
			}
		})
	}
	// 清空数据库
	async clear() {
		this.db = await this.initDataBase()
		this.db.transaction([DB_STORE_NAME], 'readwrite').objectStore(DB_STORE_NAME).clear()
	}
	// 创建数据库和表
	initDataBase() {
		if (!window.indexedDB) {
			console.log('您的浏览器不支持IndexedDB的稳定版本')
			return
		}
		let request = indexedDB.open(DB_NAME, DB_VERSION)
		return new Promise((resolve, reject) => {
			// 建立数据库连接
			request.onupgradeneeded = function (evt) {
				let db = evt.target.result
				if (!db.objectStoreNames.contains(DB_STORE_NAME)) db.createObjectStore(DB_STORE_NAME, { keyPath: 'model' })
			}
			// 连接成功
			request.onsuccess = function (evt) {
				resolve(evt.target.result)
			}
			// 连接失败
			request.onerror = function () {
				reject()
			}
		})
	}
}
